<?php

namespace App\Http\Controllers;

use App\Common\CacheKey;
use App\Http\Resources\Address as AddressResource;
use App\Http\Resources\AddressCollection;
use App\Models\Address;
use App\Models\Region;
use App\Support\Time;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;

class AddressesController extends Controller
{
    /**
     * 获取省市区数据（缓存1年）
     *
     * @return array
     */
    public function regions()
    {
        $data = Cache::remember(CacheKey::$regions, Time::MINUTES_OF_YEAR, function () {
            $regions = Region::with('children.children')
                ->where('level', Region::LEVEL_PROVINCE)->get();
            
            return $regions->toArray();
        });
        
        return $this->wrapData($data);
    }
    
    /**
     * 地址列表
     *
     * @return AddressCollection
     */
    public function index()
    {
        /** @var \App\Models\User $user */
        $user = Auth::user();
        
        $relations = ['province', 'city', 'district'];
        $paginate = $user->addresses()->with($relations)
            ->orderByDesc('is_default')->orderByDesc('id')->simplePaginate();
        
        return new AddressCollection($paginate);
    }
    
    /**
     * 创建地址
     *
     * @param Request $request
     * @return AddressResource
     */
    public function store(Request $request)
    {
        /** @var \App\Models\User $user */
        $user = Auth::user();
        
        $inputs = $this->validateAddress($request);
        
        $district = Region::find($inputs['district_id']);
        $inputs['city_id'] = $district->parent->id;
        $inputs['province_id'] = $district->parent->parent->id;
        
        // 如果没有默认地址，则设置为默认地址
        if (! $user->defaultAddress()) {
            $inputs['is_default'] = 1;
        }
        
        $address = $user->addresses()->create($inputs);
        
        return new AddressResource($address);
    }
    
    /**
     * 地址详情
     *
     * @param Address $address
     * @return AddressResource|\Illuminate\Http\JsonResponse
     */
    public function show(Address $address)
    {
        /** @var \App\Models\User $user */
        $user = Auth::user();
        if ($user->id != $address->user_id) {
            return access_denied();
        }
        
        return new AddressResource($address);
    }
    
    /**
     * 更新地址
     *
     * @param Request $request
     * @param Address $address
     * @return AddressResource|\Illuminate\Http\JsonResponse
     */
    public function update(Request $request, Address $address)
    {
        /** @var \App\Models\User $user */
        $user = Auth::user();
        if ($user->id != $address->user_id) {
            return access_denied();
        }
        
        $inputs = $this->validateAddress($request);
        
        $district = Region::find($inputs['district_id']);
        $inputs['city_id'] = $district->parent->id;
        $inputs['province_id'] = $district->parent->parent->id;
        
        // 设置默认地址
        if ($request->post('is_default')) {
            $default = $user->defaultAddress();
            
            // 取消原有默认地址
            if ($default && $address->isNot($default)) {
                $default->update(['is_default' => 0]);
            }
            
            $inputs['is_default'] = 1;
        }
        
        $address->update($inputs);
        
        return new AddressResource($address);
    }
    
    /**
     * 删除地址
     *
     * @param Address $address
     * @return \Illuminate\Http\JsonResponse|void
     *
     * @throws \Exception
     */
    public function destroy(Address $address)
    {
        /** @var \App\Models\User $user */
        $user = Auth::user();
        if ($user->id != $address->user_id) {
            return access_denied();
        }
        
        $address->delete();
        
        // 删除默认地址时，把另一个地址设置为默认地址
        if ($address->is_default && $newDefault = $user->addresses()->first()) {
            $newDefault->update(['is_default' => 1]);
        }
    }
    
    /**
     * 默认地址
     *
     * @return AddressResource|array
     */
    public function defaultAddress()
    {
        /** @var \App\Models\User $user */
        $user = Auth::user();
        
        $address = $user->defaultAddress();
        
        if (empty($address)) {
            return $this->wrapData();
        }
        
        return new AddressResource($address);
    }
    
    /**
     * 验证地址信息
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    protected function validateAddress($request)
    {
        $level = Region::LEVEL_DISTRICT;
        
        return $this->validate($request, [
            'district_id' => "required|exists:regions,id,level,$level",
            'address' => 'required|max:100',
            'consignee' => 'required|max:20',
            'phone' => 'required|phone',
        ]);
    }
}
